<?php
class PublicnewAction extends Action {
	
	public function doLogin() {
		$opt_verify = model('Xdata')->lget('siteopt');
		$opt_verify = $opt_verify['site_verify'];
		$opt_verify = in_array('login', $opt_verify);

		if ($opt_verify && md5($_POST['verify'])!=$_SESSION['verify']) {
			$out = array(
				'r'=>false,
				'm'=>'验证码错误'
			);
		   exit(json_encode($out));
		}
		
		$username =	$_POST['email'];
		$password =	$_POST['password'];
		
		if(!$password){
			$out = array(
				'r'=>false,
				'm'=>'请输入密码'
			);
		   exit(json_encode($out));
		}

		if(isValidEmail($username)){
			$user = service('Passport')->getLocalUser($username,$password);
			if(UC_SYNC && $user['uid']){
				$uc_user_ref = get_ucenter_user_ref($user['uid']);
				if($uc_user_ref['uc_uid']){
					$uc_user = uc_user_login($uc_user_ref['uc_uid'],$password,1);
					if($uc_user[0] == -1 || $uc_user[0] == -2)$uc_user_ref = array();
				}else if($user['uname']){
					$res_checkname = uc_user_checkname($user['uname']);
					if($res_checkname>=-3 && $res_checkname<=-1){
						$error_param = '用户名';
					}
					$res_checkemail = uc_user_checkemail($username);
					if($res_checkemail>=-6 && $res_checkemail<= -4){
						$error_param = $error_param?$error_param.'和Email':'Email';
					}
					if($error_param){						
						$message_data['title']   = '同步至UCenter时，'.$error_param.'不合法或已被注册';
						$message_data['content'] = '由于您在本站上的'.$error_param.'在UCenter上不合法或已被注册'.$error_param.'冲突，可到此地址 '.U('home/Account/security').'#ucenter 重新设置您在UCenter上的'.$error_param.'。';
						$message_data['to'] = $user['uid'];
						model('Message')->postMessage($message_data, M('user')->getField('uid','admin_level=1'));
					}else{
						$uc_uid = uc_user_register($user['uname'],$password,$username);
						add_ucenter_user_ref($user['uid'],$uc_uid,$user['uname']);
						$uc_user[0] = $uc_uid;
					}
				}
			}
		}

		if($user) {
			//检查是否激活
			if ($user['is_active'] == 0) {
				$out = array(
					'r'=>false,
					'm'=>'你的账户还未激活，不能快速登录！'
				);
			   exit(json_encode($out));
			}
			service('Passport')->registerLogin($user,0);
			$this->mid = $user['uid'];
			$_SESSION['userInfo'] = D('User', 'home')->getUserByIdentifier($this->mid);
			$hc = $this->headercontent();
			$update['a'] = array(
				'id'=>'header_content',
				'con'=> $hc
			);
			$out = array(
					'r'=>true,
					'm'=>'快速登录成功！',
					'update'=>$update
				);
			exit(json_encode($out));
		}else {
				$out = array(
					'r'=>false,
					'm'=>'账户或密码错误，请再试！'
				);
			   exit(json_encode($out));
		}
	}
	public function doRegister() {
				// 验证码
		$verify_option = model('Xdata')->get('siteopt:site_verify');
		if (in_array('register', $verify_option) && md5($_POST['verify']) != $_SESSION['verify'])
			$this->error('验证码错误');
		
		// 邀请码
		$invite_code = h($_REQUEST['invite_code']);
		$invite_info = null;
		
		// 是否允许注册
		$register_option = model('Xdata')->get('register:register_type');
		if ($register_option === 'closed') { // 关闭注册
			$this->error('抱歉: 本站已关闭注册');
			
		} else if ($register_option === 'invite') { //邀请注册
			// 邀请方式
			$invite_option = model('Invite')->getSet();
			if ($invite_option['invite_set'] == 'close') { // 关闭邀请
				$this->error('邀请注册功能关闭');
			} else { // 普通邀请 OR 使用邀请码
				if (!$invite_code)
					$this->error('抱歉: 目前仅接受邀请注册，请向已注册的用户索要邀请链接');
				else if (!($invite_info = $this->__getInviteInfo($invite_code)))
					$this->error('抱歉: 邀请码错误');
			}
		} else { // 公开注册
			if (!($invite_info = $this->__getInviteInfo($invite_code)))
				unset($invite_code, $invite_info);
		}
		
		// 参数合法性检查
		$required_field = array(
			'email'		=> 'Email',
			'nickname'  => '用户名',
			'password'	=> '密码',
			'repassword'=> '密码',
		);
		foreach ($required_field as $k => $v)
			if (empty($_POST[$k]))
				$this->error($v . '不可为空');

		if (!$this->isValidEmail($_POST['email']))
			$this->error('Email格式错误，请重新输入');
		if (!$this->isValidNickName($_POST['nickname']))
			$this->error('用户名不符合要求或已被使用');
		if (strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'])
			$this->error('密码必须为6-16位，且两次必须相同');
		if (!$this->isEmailAvailable($_POST['email']))
			$this->error('Email已经被使用，请重新输入');

		// 是否需要Email激活
		$need_email_activate = intval(model('Xdata')->get('register:register_email_activate'));

		// 注册
		$data['email']     = $_POST['email'];
		$data['password']  = md5($_POST['password']);
		$data['uname']	   = t($_POST['nickname']);
		$data['ctime']	   = time();
		$data['is_active'] = $need_email_activate ? 0 : 1;
		if (!($uid = D('User', 'home')->add($data)))
			$this->error('抱歉: 注册失败，请稍后重试');

		// 将用户添加到myop_userlog，以使漫游应用能获取到用户信息
		$user_log = array(
			'uid'		=> $uid,
			'action'	=> 'add',
			'type'		=> '0',
			'dateline'	=> time(),
		);
		M('myop_userlog')->add($user_log);

		// 将邀请码设置已用
		model('Invite')->setInviteCodeUsed($invite_code);
		
		// 同步至UCenter
		if (UC_SYNC) {
			$uc_uid = uc_user_register($_POST['nickname'],$_POST['password'],$_POST['email']);
			//echo uc_user_synlogin($uc_uid);
			if ($uc_uid > 0)
				add_ucenter_user_ref($uid,$uc_uid,$data['uname']);
		}

		if ($need_email_activate == 1) { // 邮件激活
			$this->activate($uid, $_POST['email'], $invite_code);
		} else {
			// 置为已登陆, 供完善个人资料时使用
			service('Passport')->loginLocal($uid);
			
			// 缓存邀请信息, 供完善个人资料后使用
			$_SESSION["invite_info_{$uid}"] = $invite_info;

			if (!is_numeric(stripos($_POST['HTTP_REFERER'], dirname('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])))) {
                //注册完毕，跳回注册页之前
                redirect($_POST['HTTP_REFERER']);
			} else {
				//注册完毕，跳转至帐号修改页
				redirect(U('home/Public/userinfo'));
			}
		}
	}
	public function index() {
		echo $this->headercontent();
	}
	public function headercontent() {
		global $ts;
		$this->getapps();
		$this->assign('ts',$ts);
		$this->assign ( 'userCount', X ( 'Notify' )->getCount ( $this->mid ) );
		$this->assign('mid',$this->mid);
		return $this->fetch('headercontent');
	}
	public function getapps() {
		global $ts;
		// 用户的应用 = 默认应用 + 用户安装的可选应用
		$default_app = model('App')->getSiteDefaultApp();
		$installed   = model('App')->getUserInstalledApp($this->mid);
		$res = array_merge($default_app, $installed);
		
		$has_installed = false;
		$user_app	   = array();
		foreach ($res as $k => $v) {
			if ($v['app_name'] == APP_NAME)
				$has_installed = true;
			
			$v['app_entry']	    = U($v['app_name'].'/'.$v['app_entry']);
			$v['admin_entry']   = U($v['app_name'].'/'.$v['admin_entry']);
			$v['sidebar_entry'] = U($v['app_name'].'/'.$v['sidebar_entry']);
			
			if ($v['status']==1) { // 站点默认应用
				$user_app['local_default_app'][] = $v;
			}else { // 用户安装的应用
				$v['display_order'] = $v['user_display_order']; // 顺序号: 用户自定义的顺序号
				unset($v['user_display_order']);
				$user_app['local_app'][] = $v;
			}
		}
		
		// 检查是否为默认应用
		if (in_array(APP_NAME, C('DEFAULT_APPS')))
			$has_installed = true;
		// 检查是否为管理后台
		if (!$has_installed && model('App')->isAppAdmin(APP_NAME, $ts['_mod']))
			$has_installed = true;
		if (!$has_installed) {
			$this->assign('jumpUrl', U('home/Index/install', array('app_name' => APP_NAME, 'app_id' => 0)));
			$this->error('您尚未添加应用，请先添加');
		}
		
		// 漫游应用
		if ($ts['site']['my_status']) {
			$default_app = model('Myop')->getAllDefaultApp();
			$myopapp     = model('Myop')->getAllInstalledByUser($this->mid);
			
			$ids = array();
			foreach ($myopapp as $v) {
				if (in_array($v['appid'], $ids))
					continue ;
				$ids[] = $v['appid'];
				$user_app['myop_app'][] = array('app_id'		=> $v['appid'], 
												'app_alias'		=> $v['appname'],
												'display_order' => $v['displayorder']);
			}
			foreach ($default_app as $v) {
				if (in_array($v['appid'], $ids))
					continue ;
				$ids[] = $v['appid'];
				$user_app['myop_default_app'][] = array('app_id'		=> $v['appid'], 
														'app_alias'		=> $v['appname'],
														'display_order' => $v['displayorder']);
			}
		}
		$ts['user_app'] = $user_app;

	}
}